package
{
	import flash.events.*;
	import flash.net.*;
	import flash.utils.ByteArray;
	
	public class Loader
	{
		private static var loader:URLLoader = new URLLoader();
		loader.dataFormat = URLLoaderDataFormat.BINARY;
		loader.addEventListener(Event.COMPLETE, completeHandler);
		loader.addEventListener(Event.OPEN, openHandler);
		loader.addEventListener(ProgressEvent.PROGRESS, progressHandler);
		loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
		loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
		loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		public static var buffer:ByteArray;
		
		public static function Load(FilePath:String):void {
			var request:URLRequest = new URLRequest(FilePath);
			/* Load a file from SWF's local path */
			
            try {
                loader.load(request);
                debug("Load File: " + FilePath);
            } catch (error:Error) {
            	debug("Unable to Load File: " + FilePath);
            	/* TODO: retry? quit? */
            }
		}
		
		private static function completeHandler(event:Event):void {
            buffer = (loader.data as ByteArray);
            Flow.Next(); /* Loader is done. */
        }

        private static function openHandler(event:Event):void {
        	/* OK */
        }

        private static function progressHandler(event:ProgressEvent):void {
        	/* OK */
            //debug("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
        }

        private static function securityErrorHandler(event:SecurityErrorEvent):void {
        	/* Error */
        }

        private static function httpStatusHandler(event:HTTPStatusEvent):void {
        	/* OK */
            //debug("httpStatusHandler: " + event);
        }

        private static function ioErrorHandler(event:IOErrorEvent):void {
        	/* Error */
            /* should we retry? */
        }
        
        private static function debug(msg:String):void {
        	np.debug.print("Loader: " + msg);
        }
	}
}